package com.zerui.manager.icc.service;

import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.zerui.manager.icc.domain.PersonInfo;
import com.zerui.manager.icc.dto.PageVO;
import com.zerui.manager.icc.dto.PersonInfoVO;
import com.zerui.manager.icc.dto.PersonQueryVO;
import com.zerui.manager.icc.properties.ICCProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("iccPersonInfoService")
public class PersonInfoService extends AbstractBase {

    @Resource
    private ICCProperties iccProperties;

    /**
     * 生成全局唯一ID
     *
     * @return
     * @throws ClientException
     */
    public Long generateID() throws ClientException {
        JSONObject joData = this.generalRequest(this.iccProperties.getPerson().getSingleGenerateIdUrl(), Method.GET, null, "data");
        return joData.getLong("id");
    }

    /**
     * 新增人员信息（基本信息）
     *
     * @param personInfo 人员信息
     * @return
     * @throws ClientException
     */
    public PersonInfo add(PersonInfo personInfo) throws ClientException {
        Assert.notNull(personInfo.getCode(), "编码不能为空");
        Assert.notNull(personInfo.getName(), "人员姓名不能为空");
        Assert.notNull(personInfo.getPaperType(), "证件类型不能为空");
        Assert.notNull(personInfo.getPaperNumber(), "证件号码不能为空");
        Assert.notNull(personInfo.getPaperAddress(), "证件地址不能为空");
        if (null == personInfo.getId()) personInfo.setId(this.generateID());// 设置主键
        this.generalRequest(this.iccProperties.getPerson().getAddUrl(), Method.POST, personInfo, "data");
        return personInfo;
    }

    /**
     * 新增人员信息（包含车辆、卡片信息）
     *
     * @param personInfo
     * @return
     * @throws ClientException
     */
    public PersonInfo saveAll(PersonInfo personInfo) throws ClientException {
        Assert.notNull(personInfo.getCode(), "编码不能为空");
        Assert.notNull(personInfo.getName(), "人员姓名不能为空");
        Assert.notNull(personInfo.getPaperType(), "证件类型不能为空");
        Assert.notNull(personInfo.getPaperNumber(), "证件号码不能为空");
        Assert.notNull(personInfo.getPaperAddress(), "证件地址不能为空");
        if (null == personInfo.getId()) personInfo.setId(this.generateID());// 设置主键
        this.generalRequest(this.iccProperties.getPerson().getSaveAllUrl(), Method.POST, personInfo, "data");
        return personInfo;
    }

    /**
     * 更新人员信息
     *
     * @param personInfo 人员信息
     * @return
     * @throws ClientException
     */
    public Boolean update(PersonInfo personInfo) throws ClientException {
        Assert.notNull(personInfo.getId(), "ID不能为空");
        Assert.notNull(personInfo.getCode(), "编码不能为空");
        Assert.notNull(personInfo.getName(), "人员姓名不能为空");
        Assert.notNull(personInfo.getPaperType(), "证件类型不能为空");
        Assert.notNull(personInfo.getPaperNumber(), "证件号码不能为空");
        Assert.notNull(personInfo.getPaperAddress(), "证件地址不能为空");
        JSONObject joData = this.generalRequest(this.iccProperties.getPerson().getUpdateUrl(), Method.PUT, personInfo, "data");
        return joData.containsKey("id");
    }

    /**
     * 删除指定ID的人员信息
     *
     * @param ids 人员ID集合
     * @return
     * @throws ClientException
     */
    public Boolean delete(Long... ids) throws ClientException {
        Assert.notNull(ids, "ID不能为空");
        Map<String, Object> joParam = new HashMap<>();
        joParam.put("openDeleteFlag", 1); // 卡、车可选删除功能开启标志, 1：开启,0:不开启， 默认不开启， 不开启时，deleteCardFlag、deleteCarFlag参数不生效
        joParam.put("deleteCardFlag", 1); // 是否删除卡片信息，1-删除，0-解绑
        joParam.put("deleteCarFlag", 1); // 是否删除车辆信息,1-删除，0-解绑
        joParam.put("ids", Arrays.asList(ids));
        this.generalRequest(this.iccProperties.getPerson().getDeleteUrl(), Method.POST, joParam, "data");
        return true;
    }

    /**
     * 查询指定ID的人员信息
     *
     * @param id 人员ID
     * @return
     * @throws ClientException
     */
    public PersonInfoVO selectById(Long id) throws ClientException {
        Assert.notNull(id, "ID不能为空");
        Map<String, String> joParam = new HashMap<>();
        joParam.put("id", String.valueOf(id));
        JSONObject joData = this.generalRequest(this.renderUrl(this.iccProperties.getPerson().getDetailUrl(), joParam), Method.GET, null, "data");
        List<PersonInfoVO> personInfos = this.convert2TypeData(joData, PersonInfoVO.class);
        return personInfos.size() > 0 ? personInfos.get(0) : null;
    }

    /**
     * 是否存在证件号码
     *
     * @param paperNumber
     * @return
     * @throws ClientException
     */
    public Boolean checkPaperNumber(final String paperNumber) throws ClientException {
        Map<String, String> joParam = new HashMap<>();
        joParam.put("paperNumber", paperNumber);
        JSONObject joData = this.generalRequest(this.renderUrl(this.iccProperties.getPerson().getDetailByNumberUrl(), joParam), Method.POST, joParam, "data");
        List<PersonInfoVO> personInfos = this.convert2TypeData(joData, PersonInfoVO.class);
        return !personInfos.isEmpty();
    }

    /**
     * 分页查询人员信息
     *
     * @param queryVO 查询条件
     * @return
     * @throws ClientException
     */
    public PageVO<PersonInfo> findPage(PersonQueryVO queryVO) throws ClientException {
        Map<String, Object> joParam = new HashMap<>();
        joParam.put("departmentId", queryVO.getDepartmentId());
        joParam.put("isContain", queryVO.getIsContain());
        joParam.put("paperTypeList", queryVO.getPaperTypeList());
        joParam.put("personTypeList", queryVO.getPersonTypeList());
        joParam.put("nationList", queryVO.getNationList());
        joParam.put("statusList", queryVO.getStatusList());
        joParam.put("sexList", queryVO.getSexList());
        joParam.put("personIdentityId", queryVO.getPersonIdentityId());
        joParam.put("biometricType", queryVO.getBiometricType());
        joParam.put("personIdList", queryVO.getPersonIdList());
        joParam.put("nameList", queryVO.getNameList());
        joParam.put("paperNumberList", queryVO.getPaperNumberList());
        joParam.put("searchKey", queryVO.getSearchKey());
        joParam.put("pageNum", queryVO.getPageNum());
        joParam.put("pageSize", queryVO.getPageSize());
        JSONObject joData = this.generalRequest(iccProperties.getPerson().getPageUrl(), Method.POST, joParam, "data");
        PageVO<PersonInfo> pageVO = new PageVO<>();
        pageVO.setCurrentPage(joData.getInteger("currentPage"));
        pageVO.setPageSize(joData.getInteger("pageSize"));
        pageVO.setTotalPage(joData.getInteger("totalPage"));
        pageVO.setTotalRows(joData.getInteger("totalRows"));
        pageVO.setPageData(this.convert2TypeData(joData.getJSONArray("pageData"), PersonInfo.class));
        return pageVO;
    }


    /**
     * 检查图片是否合格
     *
     * @param ossImgUrl 图片合格率检查
     * @return
     */
    public Boolean checkOssImg(String ossImgUrl) throws ClientException {
        Map<String, Object> joParam = new HashMap<>();
        joParam.put("fileUrl", ossImgUrl);
        joParam.put("fileType", 2);
        joParam.put("saveType", 3);
        joParam.put("ossType", 1);
        JSONObject joData = this.generalRequest(iccProperties.getPerson().getCheckImgUrl(), Method.POST, joParam, "data");
        return joData.containsKey("result");
    }

    /**
     * 上传照片
     *
     * @param file 照片文件
     * @return
     */
    public String uploadImg(MultipartFile file) {
        try {
            JSONObject joData = this.generalUpload(iccProperties.getPerson().getUploadImgUrl(), Method.POST, file.getName(), file.getBytes(), "data");
            return joData.getString("fileUrl");
        } catch (Exception e) {
            throw new BizException("上传人员照片出错", e);
        }
    }
}
